// ignore_for_file: depend_on_referenced_packages, must_be_immutable

import 'dart:convert';
import 'package:aitao_flutter/chat/view/conversation_system_item.dart';
import 'package:aitao_flutter/chat/view/conversation_user_item.dart';
import 'package:aitao_flutter/im/im_manager.dart';
import 'package:aitao_flutter/model/im/message_attachment_model.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:aitao_flutter/utils/time_utils.dart';
import 'package:flutter/material.dart';
import 'package:nim_chatkit_ui/chat_kit_client.dart';
import 'package:nim_chatkit_ui/chat_page.dart';
import 'package:nim_chatkit_ui/view/chat_kit_message_list/item/chat_kit_message_item.dart';
import 'package:nim_conversationkit_ui/conversation_kit_client.dart';
import 'package:nim_conversationkit_ui/page/conversation_page.dart';
import 'package:nim_conversationkit/repo/conversation_repo.dart';
import 'package:nim_core/nim_core.dart';

class ATChatPage extends StatefulWidget {
  ATChatPage({super.key, required this.imManager});
  IMManager imManager;
  @override
  State<ATChatPage> createState() => _ATChatPageState();
}

class _ATChatPageState extends State<ATChatPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ConversationPage(
        config: ConversationUIConfig(
            titleBarConfig:
                const ConversationTitleBarConfig(showTitleBar: false),
            itemConfig: ConversationItemConfig(itemClick: (data, position) {
              // goToP2pChat(context, data.user?.userId ?? '');
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return ChatPage(
                    sessionId: data.session.sessionId,
                    sessionType: NIMSessionType.p2p);
              })).then((value) {
                debugPrint('返回:$value');
                widget.imManager.getIMUnReadCount();
              });
              // widget.imManager.getIMUnReadCount();
              return true;
            }, customItemBuilder: (info, index) {
              if (info.session.sessionId == SpUtil.getSysId()) {
                // 系统通知
                debugPrint('info:${info.toString()}');
                return ConversationSystemItem(info: info);
                // return Text('系统消息');
              }
              // debugPrint('user1:${info.toString()}');
              return ConversationUserItem(info: info);
            })),
      ),
    );
  }

  initUnread() {
    ConversationRepo.getMsgUnreadCount().then((value) {
      if (value.isSuccess && value.data != null) {
        debugPrint('getMsgUnreadCount:$value');
      }
    });
    //messageAttachment
    ChatKitMessageBuilder messageBuilder = ChatKitMessageBuilder();
    messageBuilder.extendBuilder = {
      NIMMessageType.custom: (message) {
        ///todo 自定义message展示
        // debugPrint('message.messageAttachment.toString()');
        // debugPrint('${message.messageAttachment!.toMap()}');
        if (message.messageAttachment != null) {
          Map<String, dynamic> attachment = message.messageAttachment!.toMap();
          // debugPrint('attachment:$attachment');
          String obj = json.encode(attachment);
          // debugPrint('obj:$obj');
          Map deObj = json.decode(obj);
          // debugPrint('deObj:$deObj');
          MessageAttachmentModel model =
              MessageAttachmentModel.fromJson(deObj['data']);
          // debugPrint('model:${model.fromUid}');
          String txt = '';
          if (model.status == 3) {
            txt = '超时未接听';
          } else if (model.status == 4) {
            txt = '通话时长:${TimeUtils.formatDuration(model.callTime ?? 0)}';
          }
          if (SpUtil.getUserData().userinfo!.userId.toString() ==
              model.fromUid) {
            // 代表是自己为主叫
            if (model.status == 1) {
              txt = '已取消';
            } else if (model.status == 2) {
              txt = '对方已拒绝';
            }
          } else {
            // 代表自己为被叫
            if (model.status == 1) {
              txt = '对方已取消';
            } else if (model.status == 2) {
              txt = '已拒绝';
            }
            return Container(
              color: ColorStyle.backGroundColor,
              padding: const EdgeInsets.all(15),
              child: Text(
                txt,
                style: const TextStyle(fontSize: 14, color: Color(0xFF333333)),
              ),
            );
          }
        }
        return Container();
      }
    };
    // 设置ChatKitClient的chatUIConfig
    ChatKitClient.instance.chatUIConfig = ChatUIConfig(
      // 设置接收消息的背景
      selfMessageBg: BoxDecoration(
          color: ColorStyle.themeColor, borderRadius: RadiusStyle.radiusAll(5)),
      showP2pMessageStatus: false,
      messageTextColor: ColorStyle.whiteColor,
      receiveMessageBg: BoxDecoration(
          color: ColorStyle.backGroundColor,
          borderRadius: RadiusStyle.radiusAll(5)),
      // 头像的圆角
      avatarCornerRadius: 5,
      popMenuConfig: PopMenuConfig(
        enableForward: false,
        enablePin: false,
      ),
      messageBuilder: messageBuilder,
    );
  }

  @override
  void initState() {
    super.initState();
    initUnread();
  }
}
